// EthernetLayer.cpp: implementation of the CEthernetLayer class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "EthernetLayer.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CEthernetLayer::CEthernetLayer( char* pName )
: CBaseLayer( pName )
{
	ResetHeader( ) ;
}

CEthernetLayer::~CEthernetLayer()
{
}

void CEthernetLayer::ResetHeader()
{
	memset( m_sHeader.enet_dstaddr, 0, 6 ) ;
	memset( m_sHeader.enet_srcaddr, 0, 6 ) ;
	memset( m_sHeader.enet_data, ETHER_MAX_DATA_SIZE, 6 ) ;
	m_sHeader.enet_type = 0 ;
}

unsigned char* CEthernetLayer::GetSourceAddress()
{
	return m_sHeader.enet_srcaddr ;
}

unsigned char* CEthernetLayer::GetDestinAddress()
{

	return m_sHeader.enet_dstaddr; 
}

void CEthernetLayer::SetSourceAddress(unsigned char *pAddress)
{
	memcpy(m_sHeader.enet_srcaddr,pAddress,6);
}

void CEthernetLayer::SetDestinAddress(unsigned char *pAddress)
{
	memcpy( m_sHeader.enet_dstaddr, pAddress, 6 ) ;
}

BOOL CEthernetLayer::Send(unsigned char *ppayload, int nlength,unsigned short port)
{
	memcpy( m_sHeader.enet_data, ppayload, nlength ) ;
	memcpy( &m_sHeader.enet_type,&port,2);
	BOOL bSuccess = mp_UnderLayer->Send( (unsigned char*) &m_sHeader, nlength + ETHER_HEADER_SIZE );


	return bSuccess ;
}

BOOL CEthernetLayer::Receive( unsigned char* ppayload )
{
	PETHERNET_HEADER pFrame = (PETHERNET_HEADER) ppayload ;
	BOOL bSuccess = FALSE;
	UCHAR BroadcastMode[6];
	memset(BroadcastMode,0xff,6);

	//if( !memcmp((const char*) pFrame->enet_dstaddr , (const char*)m_sHeader.enet_srcaddr, 6) 
	//	|| !memcmp((const char*)pFrame->enet_dstaddr,BroadcastMode,6 ) && 
	//	(memcmp((const char*)pFrame->enet_srcaddr,(const char*)m_sHeader.enet_srcaddr,6 ) != 0) )
	//{
	//	bSuccess = mp_aUpperLayer[0]->Receive( (unsigned char*) pFrame->enet_data);
	//}

	if(pFrame->enet_type == 0x0800)
		bSuccess = mp_aUpperLayer[0]->Receive( (unsigned char*) pFrame->enet_data); //ip protocol
	else if(pFrame->enet_type == 0x0806)
		bSuccess = mp_aUpperLayer[1]->Receive( (unsigned char*) pFrame->enet_data); //arp protocol

	return bSuccess ;
}
